<template>
  <div ref="map"></div>
</template>

<script lang="ts">
export default {
  name: "Map"
};
</script>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { onMounted, nextTick, ref, watch } from "vue";
import { tryOnUnmounted, useTimeoutFn, useEventListener } from "@vueuse/core";
// import { postProjectModule } from "/@/api/analysis";

import {
  addResizeListener,
  removeResizeListener
} from "element-plus/lib/utils/resize-event";
import axios from "axios";
const props = defineProps({
  dataList: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(["clickItem", "cancleSelected"]);

const map = ref<HTMLElement | null>(null) as any;

let echartInstance: ECharts;

let seriesData = ref(props.dataList);
let selectedName = ref("");
let option = {} as any;
let geoData = null;

const getdata = async () => {
  if (!geoData) {
    axios.get("./json/china_1.json").then(data => {
      geoData = data.data;
      
      // echarts.registerMap("china", { geoJSON: geoData });
      echarts.registerMap("china", { geoJSON: translateMapData(geoData) });
      initechartInstance(seriesData.value);
    });
  } else {
    setOption(seriesData.value);
  }
};

function translateMapData(source) {
  const customMap = [
    {
      name: '华南生产部',
      include: ["湖北省", "湖南省", "广东省", "海南省"],
      center: [114.298572, 30.584355],
      coordinates: []
    },
    {
      name: '华东生产部',
      include: ["浙江省", "江苏省", "上海市", "安徽省", "苏沪省"],
      center: [120.153576, 30.287459],
      coordinates: []
    },
    {
      name: '华北生产部',
      include: ["天津省", "河北省", "山东省"],
      center: [117.190182, 39.125596],
      coordinates: []
    },
    {
      name: '东北生产部',
      include: ["内蒙古自治区", "辽宁省", "黑吉省"],
      center: [123.429096, 41.796767],
      coordinates: []
    },
    {
      name: '西北生产部',
      include: ["山西省", "晋陕省", "陕西省", "甘青藏省", "甘肃省", "宁夏回族自治区", "西藏", "河南省"],
      center: [123.429096, 41.796767],
      coordinates: []
    },
    {
      name: '西南生产部',
      include: ["四川省", "贵州省", "广西壮族自治区"],
      center: [104.065735,30.659462],
      coordinates: []
    },
    {
      name: '总部/喜力生产部',
      include: ["北京市"],
      center: [116.405285, 39.904989],
      coordinates: []
    }
  ]
  customMap.forEach(item => {
    source.features.forEach(targetItem => {
      if (item.include.includes(targetItem.properties.name)) {
        if(['甘青藏省', '黑吉省', '内蒙古自治区', '晋陕省'].includes(targetItem.properties.name)) {
          item.coordinates.push(targetItem.geometry.coordinates)
        } else {
          item.coordinates = item.coordinates.concat(targetItem.geometry.coordinates)
        }
        targetItem.isJoin = true
      }
    })
  })
  const transleted = customMap.map(item => {
    return {
      type: "Feature",
      properties: {
        name: item.name,
        center: item.center
      },
      geometry: {
        type: "MultiPolygon",
        coordinates: item.coordinates
      }
    }
  })
  return {
    type: "FeatureCollection",
    features: [...transleted, ...source.features.filter(item => !item.isJoin)]
  }
}

function initechartInstance(seriesData) {
  seriesData.forEach(item => {
    if (item.name === '喜力生产部') {
      item.name = '总部/喜力生产部'
    }
  })
  const setHtml = {
    // width: 500
    // height: 500
  };
  const echartDom = document.querySelector(".map");
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom, null, setHtml);
  echartInstance.clear(); //清除旧画布 重新渲染
  // var dataList = [
  //   { name: "苏沪", selected: true, value: "150" },
  //   { name: "黑吉", selected: true, value: "75" },
  //   { name: "四川省", selected: true, value: "8" },
  //   { name: "甘青藏", selected: true, value: "3" },
  //   { name: "广东省", selected: true, value: "300" },
  //   { name: "河北省", selected: true, value: "80" },
  //   { name: "北京市", selected: true, value: "8" }
  // ];
  option = {
    tooltip: {
      backgroundColor: "rgba(0, 21, 43, 0.6)",
      borderColor: "#8895B7",
      formatter: function (params) {
        var nameArr = params.seriesName.split(",");
        var num1 = 0;
        if (!isNaN(params.value)) {
          num1 = params.value;
        }
        let index = params.name.indexOf("省");
        let name = index > -1 ? params.name.slice(0, index) : params.name;
        name = name.indexOf("总部基地项目组") > -1 ? name : name + "<br />";
        return name + nameArr[0] + "：" + num1;
      },
      textStyle: {
        color: "#FDFDFF",
        fontSize: "14px"
      },
      extraCssText: "box-shadow: 0px 0px 7px 0px rgba(136,149,183,0.3);"
    },
    visualMap: {
      min: 0,
      max: 20,
      bottom: 100,
      text: ["高", "低"],
      inRange: {
        color: ["#eff1ff", "#5298FF"]
      },
      show: true
    },
    geo: {
      map: "china",
      roam: false, //不开启缩放和平移
      zoom: 1, //视角缩放比例
      label: {
        show: false,
        formatter: params => {
          let index = params.name.indexOf("省");
          let name = index > -1 ? params.name.slice(0, index) : params.name;
          name = name.indexOf("总部基地项目组") > -1 ? name : name;
          return name;
        }
      },
      itemStyle: {
        areaColor: "#fff",
        borderColor: "#90adff"
      },
      // layoutCenter: ['50%', '46%'],
      // layoutSize: "50%",
      emphasis: {
        label: {
          show: true,
          color: "#000"
        },
        itemStyle: {
          areaColor: "#3E8CFF" //鼠标hover颜色#5298FF
        }
      },
      selectedMode: "single",
      select: {
        itemStyle: {
          areaColor: "#3E8CFF",
          borderColor: "#3E8CFF"
        },
        label: {
          color: "#000"
        }
      }
    }
  };
  setOption(seriesData);

  echartInstance.on("click", function (params) {
    console.log("####", params);
    selectedName.value = params.name;
    emit("clickItem", params.data, params.name);
  });
  // 监听点击非地图区域
  echartInstance.getZr().on("click", function (event) {
    if (!event.target) {
      echartInstance.dispatchAction({
        type: "unselect",
        name: selectedName.value
      });
      emit("cancleSelected", selectedName.value);
    }
  });
}

const setOption = seriesData => {
  option.series = [
    {
      name: "数量",
      type: "map",
      geoIndex: 0,
      map: "china",
      coordinateSystem: "geo",
      data: seriesData
    }
  ];
  echartInstance.setOption(option);
};

watch(
  () => props.dataList,
  newVal => {
    seriesData.value = newVal;
    getdata();
  }
);

onMounted(() => {
  nextTick(() => {
    addResizeListener(map.value, resetRender);
  });
  useEventListener("resize", () => {
    resetRender();
  });
});

const resetRender = () => {
  if (!echartInstance) return;
  useTimeoutFn(() => {
    echartInstance.resize();
  }, 180);
};

const setMapSelect = name => {
  selectedName.value = "";
  echartInstance.dispatchAction({
    type: "select",
    name
  });
};
const setMapUnSelect = name => {
  echartInstance.dispatchAction({
    type: "unselect",
    name
  });
};
defineExpose({ setMapSelect, setMapUnSelect });

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
  removeResizeListener(map.value, resetRender);
});
</script>

<style scoped></style>
